<?php namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model {
	protected $table = 'users'; //表名
	protected $primaryKey = 'id'; //索引

	protected $returnType = 'array'; //返回类型
	protected $useSoftDeletes = true; //使用软删除？表内要有deleted列

	protected $allowedFields = ['username','password','avatar', 'email', 'group', 'zone', 'deleted']; //允许更新写入的列

	protected $useTimestamps = false; //使用时间戳

	protected $validationRules = []; //验证规则
	protected $validationMessages = []; //验证返回信息
	protected $skipValidation = false; //在所有插入和更新期间，应跳过其他验证

	protected $beforeInsert = ['hashPassword']; //
	protected $beforeUpdate = ['hashPassword'];

	protected $session;

	protected function hashPassword(array $data) {
		if (isset($data['data']['password'])) {
			$data['data']['password'] = password_hash($data['data']['password'], PASSWORD_DEFAULT);
			//unset($data['data']['password']);
		}
		return $data;
	}

	public function checkLogin() {
		$session = \Config\Services::session();

		$user = $session->get('user');

		if (!isset($user['logged_in']) || !$user['logged_in']) {
			return false;
		} else {
			return $user;
		}
	}

	public function doLogin($username, $password, $remember = 7200) {
		if (!$username) {
			return ['message' => '邮箱必须填写。', 'status' => 'Error'];
		}

		if (!$password) {
			return ['message' => '密码必须填写。', 'status' => 'Error'];
		}

		$user = $this->where(['username' => $username])->first();

		if (!$user) {
			return ['message' => '邮箱未注册。', 'status' => 'Error'];
		}

		if ($user['password'] != md5($password)) {
			return ['message' => '密码错误。', 'status' => 'Error'];
		}

		unset($user['password']);
		$user['logged_in'] = true;

		$groupModel = new \App\Models\GroupModel();
		$user['group'] = $groupModel->find($user['group']);

		$session = \Config\Services::session();
		$session->sessionExpiration = $remember;
		$session->set('user', $user);

		return ['message' => '登录成功。', 'status' => 'Success'];
	}

}
